import * as AdminAPI from '@/api/admin.js'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 用户登录
  login({commit}, userInfo) {
    const { name, password} = userInfo
    return AdminAPI.login({
      name: name.trim(),
      password: password
    }).then(response => {
      const {data} = response
      commit('SET_TOKEN', data.token)
      setToken(data.token)
    })
  },

  // 查询用户信息
  getInfo({commit,state}) {
    return AdminAPI.getInfo().then(response => {
        const {data} = response
        if (!data) {
          return Promise.reject('查询用户信息失败, 请重新登录!')
        }
        const { name, avatar } = data
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        Promise.resolve(data)
      })
  },

  // 用户登出
  logout({
    commit,
    state
  }) {
    return AdminAPI.logout(state.token).then(() => {
        removeToken(); //清除本地存储的token
        resetRouter(); //重置路由数据
        commit('RESET_STATE'); //重置用户状态（token、name、avatar)       
      })   
  },

  //重置token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken(); //清除本地存储的token
      commit('RESET_STATE'); //重置用户状态（token、name、avatar)
      resolve(); //成功
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
